from django.shortcuts import render
from django.views import View
from django import http
from meiduo_mall.utils.response_code import RETCODE
from django.core.cache import cache
from . import constants
from .models import Area


class AreaView(View):
    def get(self, request):

        area_id = request.GET.get('area_id')
        if area_id:
            sub_data = cache.get('area_' + area_id)
            if sub_data is None:
                try:
                    area = Area.objects.get(pk=area_id)


                except:
                    return http.JsonResponse({
                        'code': RETCODE.PARAMERR,
                        'errmsg': '无效的地区编码'
                    })
                subs = area.subs.all()
                sub_list = []
                for sub in subs:
                    sub_list.append({
                        'id': sub.id,
                        'name': sub.name
                    })
                sub_data = {
                    'id': area.id,
                    'name': area.name,
                    'subs': sub_list
                }

                cache.set('area_' + area_id, sub_data, constants.AREA_CACHE_EXPIRES)
            return http.JsonResponse({
                'code': RETCODE.OK,
                'errmsg': 'ok',
                'sub_data': sub_data
            })
        else:
            province_list = cache.get('province_list')

        if province_list is None:
            provinces = Area.objects.filter(parent__isnull=True)
            province_list = []
            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name

                })
        cache.set('province_list', province_list, constants.AREA_CACHE_EXPIRES)
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'ok',
            'province_list': province_list
        })
